<template>
    <div>
      <el-row type="flex" justify="space-between" style="text-align: left;">
          <el-col :span="12" style="height: 50px;">
              <h2 style="margin: 0;">物品借用</h2>
          </el-col>
          <el-col :span="12" style="text-align: right;height: 50px;">
              <el-button-group v-if="!readonly">
                  <el-button type="primary" @click="saveApplication">保存</el-button>
                  <el-button type="primary" @click="submitApplication">提交</el-button>
              </el-button-group>
              &nbsp;&nbsp;
              <el-button type="primary" @click="reback">取消</el-button>
          </el-col>
      </el-row>
      <el-row>
          <el-col :span="20" :offset="2">
              <el-form ref="form" :model="applicationForm" label-width="80px" class="demo-form-inline" :rules="rules">
                  <el-row :gutter="20">
                      <el-col :span="12">
                          <el-form-item label="申请名称"> 
                              <el-input v-model="applicationForm.applicationName" readonly style="width: 100%"></el-input>
                          </el-form-item>
                      </el-col>
                      
                  </el-row>
                  <el-row :gutter="20">
                      <el-col :span="12">
                          <el-form-item label="申请人"> 
                              <el-input v-model="applicationForm.applicationEName" readonly></el-input>
                          </el-form-item>
                      </el-col>
                      <el-col :span="12">
                          <el-form-item label="申请部门"> 
                              <el-input v-model="applicationForm.dName" readonly></el-input>
                          </el-form-item>
                      </el-col>
                      
                  </el-row>
                  <el-row :gutter="20">
                      <el-col :span="12">
                          <el-form-item label="申请时间"> 
                              <el-input v-model="applicationForm.applicationTime" readonly></el-input>
                          </el-form-item>
                      </el-col>
                      <el-col :span="12">
                          <el-form-item label="借用类型" prop="borrowType">
                              <el-select v-model="applicationForm.borrowType" placeholder="请选择" style="width: 100%" :disabled="readonly">
                                  <el-option
                                  v-for="item in borrowTypes"
                                  :key="item.value"
                                  :label="item.label"
                                  :value="item.value">
                                  </el-option>
                              </el-select>
                          </el-form-item>
                      </el-col>
                      
                      
                  </el-row>
                  <el-row :gutter="20">
                      <el-col :span="12">
                          <el-form-item label="借用仓库" prop="warehouseId">
                              <el-select v-model="applicationForm.warehouseId" placeholder="请选择" style="width: 100%" @change="getHousekeeper" :disabled="readonly">
                                  <el-option
                                  v-for="item in warehouses"
                                  :key="item.warehouseId"
                                  :label="item.warehouseName"
                                  :value="item.warehouseId">
                                  </el-option>
                              </el-select>
                          </el-form-item>
                      </el-col>
                      <el-col :span="12">
                          <el-form-item label="仓管员"> 
                              <el-input v-model="warehouseManager" readonly></el-input>
                          </el-form-item>
                      </el-col>
                  </el-row>
                  <el-row>
                      <el-col :span="24">
                          <el-form-item label="备注"> 
                              <el-input type="textarea" v-model="applicationForm.comment" :disabled="readonly"></el-input>
                          </el-form-item>
                      </el-col>
                  </el-row>
              </el-form>
          </el-col>
      </el-row>
      <el-row type="flex" justify="space-between" align="middle">
          <el-col :span="10" :offset="2"> 
              <h3 style="text-align: left;">借用列表</h3>
          </el-col>
          <el-col :span="10" style="text-align: right;"> 
              <el-button-group v-if="!readonly">
                  <el-button type="primary" @click="history">个人借用记录</el-button>
                  <el-button type="primary" @click="addGoods">新增</el-button>
                  <el-button type="primary" @click="delGoods">删除</el-button>
              </el-button-group>
          </el-col>
          <el-col :span="2"></el-col>
      </el-row>
  
      <el-row>
          <el-col :span="16" :offset="4"> 
              <el-table
                  ref="multipleTable"
                  height="250px"
                  :data="applicationGoods"
                  tooltip-effect="dark"
                  style="width: 100%"
                  stripe
                  border
                  highlight-current-row
                  @selection-change="handleSelectionChange">
                  <el-table-column
                  type="selection"
                  align="center"
                  width="55">
                  </el-table-column>
                  <el-table-column
                  type="index"
                  label="序号"
                  align="center"
                  width="60">
                  </el-table-column>
                  <el-table-column
                  prop="warehouseName"
                  label="仓库名称"
                  align="center">
                  </el-table-column>
                  <el-table-column
                  prop="goodsName"
                  label="物资名称"
                  align="center">
                  </el-table-column>
                  <!-- 可编辑列 -->
                  <el-table-column
                  label="借用数量"
                  align="center"
                  >
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.brNum" :min="1" :max="scope.row.goodsNum" :disabled="readonly"></el-input-number>
                  </template>
                  </el-table-column>
                  </el-table>
          </el-col>
      </el-row>
        <el-dialog title="个人申请记录查看" :visible.sync="historyVisible" :before-close="historyClose">
            <el-table :data="historyData" height="300px">
                <el-table-column align="center" type="index" width="50"></el-table-column>
                <el-table-column align="center" property="goodsId" label="物资编号"></el-table-column>
                <el-table-column align="center" property="goodsName" label="物资名称" ></el-table-column>
                <el-table-column align="center" property="warehouseName" label="所属仓库" width="120" ></el-table-column>
                <el-table-column align="center" property="applicationEName" label="申请人"></el-table-column>
                <el-table-column align="center" property="auditEName" label="审核人"></el-table-column>
                <el-table-column align="center" property="optionTime" label="审核日期"></el-table-column>
                <el-table-column align="center" property="optionType" label="操作类型"></el-table-column>
            </el-table>
        </el-dialog>
      <AddBorrowGoods :isShow="dialogVisible" :warehouseId="applicationForm.warehouseId" :warehouseName="applicationForm.warehouseName" @addGoods="saveData" @clossDialog="clossDialog"></AddBorrowGoods>
    </div>
  </template>
  
  <script>
  import AddBorrowGoods from '@/views/wzgl/AddBorrowGoods.vue'
  export default {
      name: 'AddorEditBApplication',
      components:{
          AddBorrowGoods,
      },
  
      data(){
          return{
              dialogVisible:false,
              applicationForm:{
                  applicationId:0,
                  applicationName:'',
                  applicationEmpNo:0,
                  applicationEName:'',
                  deptNo:0,
                  dName:'',
                  warehouseId:1,
                  warehouseName:'固定资产仓库',
                  applicationTime:'',
                  comment:'',
                  borrowType:1,
                  checkType:0,
              },
              applicationGoods:[],
              
              borrowTypes:[],
              warehouses:[],
              warehouseManager:"",
              user:{
                  empno:0,
                  ename:"",
                  deptno:0,
                  dname:""
              },
              checkData:[],
              readonly:false,
              historyVisible:false,
              historyData:[],
              rules:{
                borrowType: [
                  { required: true, message: '请选择借用类型', trigger: 'change' }
                ],
                warehouseId: [
                  { required: true, message: '请选择仓库', trigger: 'change' }
                ],
              }
              
          }
      },
      watch:{
          "applicationForm.warehouseId":{
              handler(newVal,oldVal){
                  for (let i = 0; i < this.warehouses.length; i++) {
                      if (this.warehouses[i].warehouseId == newVal){
                          this.applicationForm.warehouseName = this.warehouses[i].warehouseName
                      }
                  }
              }
          }
      },
      methods:{
          query(){
          },
          reback(){
            this.$router.push({
                path:"/borrowApplicationManager"
            })
          },
  
          getBorrowType(){
              this.$http.get("/lc/getBorrowType").then(res => {
                for (let type of res.data){
                    type.value = type.warehouseId
                    type.label = type.warehouseName
                }
                  this.borrowTypes = res.data
              }).catch(e => {
                console.log('未能正常获取借出类型信息')
              })
          },
          getWarehouse(){
              this.$http.get("/lc/queryWarehouse").then(res => {
                  this.warehouses = res.data;
              }).catch(err => {
                console.error("Error getting warehouses:", err);
                this.$message.error("获取仓库信息失败: " + err.message);
              })
          },
          getHousekeeper(val){
              this.applicationGoods = []
            //   console.log(this.applicationGoods)
              this.$http.get("/lc/queryHouseKeeperByHouseId?warehouseId="+val).then(res => {
                  // console.log(res.data);
                  let houseKeeperstr = "";
                  for (let emp of res.data){
                      houseKeeperstr += emp.ename+" ";
                  }
                  this.warehouseManager = houseKeeperstr;
              }).catch(err => {
                console.error("Error getting housekeepers:", err);
                this.$message.error("获取仓管员信息失败: " + err.message);
              })
          },
          history(){

            this.$http.get("/lc/getHistoryBRGoods?empNo="+this.user.empno).then(res => {
                this.historyData = res.data;
                this.historyVisible = true;
            }).catch(err => {
              console.error("Error getting history:", err);
              this.$message.error("获取借用历史失败: " + err.message);
            })
          },
          historyClose(){
            this.historyVisible = false;
          },
          addGoods(){
              if (this.applicationForm.warehouseId == 0 || this.applicationForm.warehouseId == null){
                  this.$message.error("请选择仓库！");
                  return;
              }
              this.dialogVisible = true;
              
          },
          saveData(val){
            for (let goods of val){
                let exists = false;
                for (let existingGoods of this.applicationGoods) {
                    if (existingGoods.goodsId === goods.goodsId) {
                        exists = true;
                        break;
                    }
                }
                
                if (!exists) {
                    goods.brNum = 1;
                    this.applicationGoods.push(goods);
                    // console.log(goods)
                }
            }  
          },
          clossDialog(){
              this.dialogVisible = false;
          },
          delGoods(){
            let newApplicationGoods = []
            for(let goods of this.applicationGoods){
                let exist = false
                for (let delGoods of this.checkData){
                    if(goods.goodsId == delGoods.goodsId){
                        exist = true
                    }
                }
                if(!exist){
                    newApplicationGoods.push(goods)
                }
                this.applicationGoods = [...newApplicationGoods]
            }
          },
          saveApplication(){ 
            if (this.applicationGoods.length == 0){
                this.$message.error("请添加物品")
                return
            }
            let saveData = {}
            this.applicationForm.checkType = 1
            // this.applicationForm.auditEmpNo = this.user.empno
            saveData.application = this.applicationForm
            for (let goods of this.applicationGoods){
                goods.optionType = "借出"
                goods.isReturn = 0
            }
            saveData.applicationGoods = this.applicationGoods
            // console.log(saveData)
            this.$http.post("/lc/addApplication",saveData).then(res => { 
                // console.log(res.data)
                
                if (res.data.statu){
                    this.$message.success("保存成功")
                    
                    this.applicationForm.applicationId = res.data.applicationId
                }
            }).catch(err => {
              console.error("Error saving application:", err);
              this.$message.error("保存申请失败: " + err.message);
            })
          },
          submitApplication(){ 
            if (this.applicationGoods.length == 0){
                this.$message.error("请添加物品")
                return
            }
            let saveData = {}
            this.applicationForm.checkType = 2
            // this.applicationForm.auditEmpNo = 0
            // this.applicationForm.bannedReason = ""
            // this.applicationForm.checkTime = ''
            // this.applicationForm.auditEmpNo = this.user.empno
            saveData.application = this.applicationForm
            for (let goods of this.applicationGoods){
                goods.optionType = "借出"
                goods.isReturn = 0
            }
            saveData.applicationGoods = this.applicationGoods
            // console.log(saveData)
            this.$http.post("/lc/addApplication",saveData).then(res => { 
                // console.log(res.data)
                
                if (res.data.statu){
                    this.$router.push({
                        path:"/borrowApplicationManager",
                        query:{
                            msg:"提交成功"
                        }
                    })
                }
            }).catch(err => {
              console.error("Error submitting application:", err);
              this.$message.error("提交申请失败: " + err.message);
            })
          },
          handleSelectionChange(val){
              this.checkData = val
          },
          getDName(){
              this.$http.get("/lc/getDeptName?deptNo="+this.user.deptno).then(res => {
                this.user.dname = res.data
                this.applicationForm.dName = this.user.dname
              }).catch(err => {
                console.error("Error getting department name:", err);
                this.$message.error("获取部门名称失败: " + err.message);
              })
          },
  
      },
      mounted(){
          if (this.$route.query.applicationInfo != null){
              this.applicationForm = this.$route.query.applicationInfo
              this.getHousekeeper(this.applicationForm.warehouseId)
          } else {
                if (this.$route.query.applicationName != null){
                this.applicationForm.applicationName = this.$route.query.applicationName
                }
                let date = new Date();
                //生成yyyy-mm-dd 格式的日期
                let dateStr = date.getFullYear() + "-"
                if (date.getMonth() < 9){
                    dateStr += "0" + (date.getMonth() + 1)
                } else {
                    dateStr += (date.getMonth() + 1)
                }
                if (date.getDate() < 10){
                    dateStr += "-0" + date.getDate()
                } else {
                    dateStr += "-" + date.getDate()
                }
                this.user.empno = localStorage.getItem('empno')
                this.user.ename = localStorage.getItem('ename')
                this.user.deptno = localStorage.getItem('deptno')
                this.getDName()
                this.applicationForm.applicationTime = dateStr
                this.applicationForm.applicationEmpNo = this.user.empno
                this.applicationForm.applicationEName = this.user.ename
                this.applicationForm.deptNo = this.user.deptno
        }
        if (this.$route.query.readonly != null){
        this.readonly = true
        }
        this.getBorrowType()
        this.getWarehouse()
        this.getHousekeeper(this.applicationForm.warehouseId)

        //   console.log(this.$route.query.applicationGoods)
        if (this.$route.query.applicationGoods != null){
            this.applicationGoods = this.$route.query.applicationGoods
        }
        // console.log(this.applicationForm)
        
      }
  }
  </script>
  
  <style>
  
  </style>